package studio.raptor.ddal.dashboard.log.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import studio.raptor.ddal.core.log.bo.ConnPoolLogData;
import studio.raptor.ddal.dashboard.log.bo.ConnPoolLogExtendData;
import studio.raptor.ddal.dashboard.log.bo.LogMessageObject;
import studio.raptor.ddal.dashboard.log.bo.SqlProcessLogExtendData;
import studio.raptor.ddal.dashboard.log.common.LogServerConstant;
import studio.raptor.ddal.dashboard.log.service.interfaces.ILogReceiveService;
import studio.raptor.ddal.dashboard.log.service.interfaces.ILogManagerService;
import javax.annotation.Resource;

@Service
public class LogReceiveService implements ILogReceiveService {

	private static Logger log = LoggerFactory.getLogger(LogReceiveService.class);

	@Resource
	private ILogManagerService logManagerService;

	/**
	 * 接收客户日志端方法
	 * @param sqlProcessLogExtendData
	 */
	public void receiveObject(SqlProcessLogExtendData sqlProcessLogExtendData){
		LogMessageObject logMessageObject = new LogMessageObject();
		logMessageObject.setSqlProcessLogExtendData( sqlProcessLogExtendData );
		//将接收到的对象写入队列
		writeObject( logMessageObject );
	}

	public void receiveObject(ConnPoolLogExtendData connPoolLogExtendData){
		LogMessageObject logMessageObject = new LogMessageObject();
		logMessageObject.setConnPoolLogExtendData( connPoolLogExtendData );
		//将接收到的对象写入队列
		writeObject( logMessageObject );
	}

	public void writeObject(LogMessageObject logMessageObject){
		for(int i = 0; i< LogServerConstant.DATABASETYPES.length; i++){
			String databaseType = LogServerConstant.DATABASETYPES[i];
			if(databaseType!=null&&!databaseType.equals("")){
				databaseType = databaseType.toUpperCase();
				String frontDataQueueName = LogServerConstant.LOG_SERVER_FRONT_DATA_QUEUE_NAME+"_"+databaseType;
				int queueLength = logManagerService.getQueueLength(frontDataQueueName);
				if("TRUE".equals(LogServerConstant.LOG_SERVER_JAVAQUEUE_LENGTH_CONTROL.toUpperCase())&&
						queueLength>LogServerConstant.LOG_SERVER_JAVAQUEUE_LENGTH){
					log.debug( "LogServerConstant.LOG_SERVER_JAVAQUEUE_LENGTH_CONTROL="+LogServerConstant.LOG_SERVER_JAVAQUEUE_LENGTH_CONTROL  );
					log.debug( "LogServerConstant.LOG_SERVER_JAVAQUEUE_LENGTH="+LogServerConstant.LOG_SERVER_JAVAQUEUE_LENGTH );
					log.debug( "queueLength="+queueLength+" 超过队列深度限制,新数据直接放弃写入！"  );
				}else{
					logManagerService.writeObject(frontDataQueueName, logMessageObject);
				}
			}
		}
	}

}
